package com.socket.nio.nio.chat.example2.server.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.socket.nio.nio.chat.example2.message.GroupChatRequestMessage;
import com.socket.nio.nio.chat.example2.message.GroupChatResponseMessage;
import com.socket.nio.nio.chat.example2.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * @author Hexudong
 * @date 2025/5/18
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage message) throws Exception {
    List<Channel> channelList = GroupSessionFactory.getGroupSession().getMembersChannel(message.getGroupName());

    if (CollectionUtil.isNotEmpty(channelList)) {
      for (Channel channel : channelList) {
        channel.writeAndFlush(GroupChatResponseMessage.builder()
            .from(message.getFrom())
            .content(message.getContent())
            .build());
      }
    }
  }
}
